#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef unsigned long long ull;
#define endl "\n";

const ull mod = 998244353;
const int N = 2e5 + 5;

int cnt[N];
int len[N];
int m;

void dfs1(int u,int cur_len,vector<vector<int>>& adj) {
    len[u] = cur_len;
    if (adj[u].empty()) { 
        cnt[u] = 1;
        return;
    }
    
    cnt[u] = 0;
    for (int v : adj[u]) {
        dfs1(v, cur_len + 1,adj);
        cnt[u] += cnt[v];
    }
}

int getk(int u,int k,vector<vector<int>>& adj) {
    if (adj[u].empty()) {
        return len[u]; 
    }
    
    for (int v : adj[u]) {
        if (k <= cnt[v]) {
            return getk(v,k,adj);
        }
        k -= cnt[v];
    }
    return -1; 
}


void dfs2(int u,ull cur_hash,vector<vector<int>>& adj,vector<ull>& hashes) {
    if (adj[u].empty()) {
        hashes.push_back(cur_hash);
        return;
    }
    
    for (int i = 0; i < adj[u].size(); ++i) {
        int v = adj[u][i];
        ull c = i + 1;
        ull new_hash = cur_hash * mod + c; 
        dfs2(v, new_hash, adj, hashes);
    }
}

void clear(vector<vector<int>>& adj) {
    for (int i = 1; i <= m; ++i) {
        cnt[i] = 0;
        len[i] = 0;
        adj[i].clear();
    }
}

void solve() {
    cin >> m;
    vector<vector<int>>adj(m+1);
    for (int i = 2; i <= m; ++i) {
        int f;
        cin >> f;
        adj[f].push_back(i);
    }
    
    dfs1(1,1,adj); 
    
    auto cmp=[&](int x,int y){
        int mn = min(cnt[x], cnt[y]);
        for (int k = 1; k <= mn; k++) {
            int lx = getk(x,k,adj);
            int ly = getk(y,k,adj);
            if (lx != ly) {
                return lx < ly;
            }
        }
        if (cnt[x] != cnt[y]) {
            return cnt[x] < cnt[y];
        }
        return x < y;
    };

    for (int i = 1; i <= m; i++) {
        sort(adj[i].begin(), adj[i].end(), cmp);
    }
    
    vector<ull> hashes;
    for (int i = 0; i < adj[1].size(); i++) {
        int v = adj[1][i];
        ull c = i + 1; 
        dfs2(v, c, adj, hashes);
    }
    
    cout << hashes.size() << "\n";
    for (ull h : hashes) {
        cout << h << "\n";
    }
    
    clear(adj);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    
    int t;
    cin >> t;
    while (t--) {
        solve();
    }
    
    return 0;
}
